using Cysharp.Threading.Tasks;
using UnityEngine;

namespace Game {
	public sealed class TurretGun : MonoBehaviour {
		public float ShootInterval = 0.25f;
		public float MaxDistance = 30;
		public int Damage = 10;
		public LineRenderer ShootLine;

		float _lastShootTime;
		AudioSource _audio;
		SecurityTurret _owner;

		private void Awake() {
			ShootLine.enabled = false;
			_audio = GetComponent<AudioSource>();
			_owner = GetComponentInParent<SecurityTurret>();
		}

		public bool CanShoot() {
			if ( Time.time - _lastShootTime < ShootInterval ) {
				return false;
			}
			return true;
		}

		public bool Shoot() {
			if ( !CanShoot() ) {
				return false;
			}
			_ = ShootEffect();
			_lastShootTime = Time.time;

			if ( !GameManager.Instance.IsServer ) {
				return true;
			}

			if ( !Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out var hit, MaxDistance, CommonStaticData.Instance.AllCollisionsMask, QueryTriggerInteraction.Ignore) ) {
				return true;
			}
			var receiver = hit.collider.GetComponent<IDamageReceiver>();
			if ( receiver != null ) {
				receiver.ApplyDamage(new DamageDescription(_owner.ID, _owner.Team, Damage, hit.point, hit.normal));
			}
			return true;
		}

		async UniTask ShootEffect() {
			ShootLine.enabled = true;
			_audio?.Play();
			await UniTask.Delay(100);
			if ( ShootLine ) {
				ShootLine.enabled = false;
			}
		}
	}
}
